import ReplayKit
import AVFoundation

class ReplayKitHelper {
    
//    static var image:UIImage?
    
    static func isRecording() -> Bool {
        return RPScreenRecorder.shared().isRecording
    }
    
    static func startCapture(imageHandler: ((UIImage?)-> Void)?) {
        do {
//            image = nil
            
            // 定义捕获处理程序
            let captureHandler: (CMSampleBuffer, RPSampleBufferType, Error?) -> Void = { sampleBuffer, bufferType, error in
                if let error = error {
                    print("Capture error: \(error.localizedDescription)")
                    return
                }

                // 处理捕获的数据
                switch bufferType {
                case .video:
                    // 处理视频样本缓冲区
                    // 可以在这里将视频数据保存到文件或者进行其他处理
                    var image = captureScreenshot(sampleBuffer: sampleBuffer)
                    print("image = \(image)")
                    if (image != nil) {
                        imageHandler?(image)
                        
                        stopCapture()
                        
                        image = nil
                    }
                    break
                case .audioApp:
                    // 处理应用程序音频样本缓冲区
                    // 可以在这里对音频数据进行处理或者保存到文件
                    break
                default:
                    break
                }
            }
            try RPScreenRecorder.shared().startCapture(handler: captureHandler)
            print("Capture started successfully")
        } catch {
            print("Failed to start capture: \(error.localizedDescription)")
        }
    }
    
   private static func captureScreenshot(sampleBuffer: CMSampleBuffer) -> UIImage? {
            guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
                print("Failed to get image buffer")
                return nil
            }

            let ciImage = CIImage(cvImageBuffer: imageBuffer)
            let context = CIContext()
            if let cgImage = context.createCGImage(ciImage, from: ciImage.extent) {
                let screenshot = UIImage(cgImage: cgImage)
                return screenshot
            } else {
                return nil
            }
        }

    static func stopCapture() {
        if (isRecording()) {
            do {
                try RPScreenRecorder.shared().stopCapture()
            } catch {
                print("Failed to start capture: \(error.localizedDescription)")
            }
        }
    }
}
